package com.toommi.refuse.controller;

import com.toommi.refuse.annotation.PermissionController;
import com.toommi.refuse.annotation.PermissionReport;
import com.toommi.refuse.common.response.CommonResponse;
import com.toommi.refuse.exception.AppUserException;
import com.toommi.refuse.model.AppUserModel;
import com.toommi.refuse.service.AppUserService;
import com.toommi.refuse.tools.SignUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * ..
 * APP端用户接口
 *
 * @author yangg
 * @since 2019-07-23 15:38
 */
@RestController
@RequestMapping(value = "")
@Slf4j
@AllArgsConstructor
@PermissionController(groupCode = "admin_app_user", groupName = "APP用户管理")
@Api(tags = "APP端用户接口")
public class AppUserController {

    private AppUserService appUserService;


    /**
     * 小程序授权
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/xcxsq")
    public CommonResponse xcxsq(HttpServletRequest request) {
        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(appUserService.CommonResponse(request));
        } catch (AppUserException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("add user error, :{}", e);
            commonResponse = CommonResponse.serverError();
        }

        return commonResponse;

    }

    /**
     * 回收端授权
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/hssq")
    public CommonResponse hssq(HttpServletRequest request) {
        CommonResponse commonResponse = CommonResponse.success();
        try {
            commonResponse.setData(appUserService.hssq(request));
        } catch (AppUserException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("add user error, :{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }

    /**
     * 服务器配置接口--get
     *
     * @param request
     * @param response
     * @throws Exception
     */

    @RequestMapping(value = "/subscribe", method = RequestMethod.GET)
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        log.info("请求进来了...");
        // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败
            if (SignUtil.checkSignatrue(signature, timestamp, nonce)) {
                out.print(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
            out = null;
        }
    }

    /**
     * 服务器配置接口--post(接收关注推送消息)
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(method = RequestMethod.POST)
    public void doPost(HttpServletRequest request, HttpServletResponse response) {

        // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String signature = request.getParameter("signature");
        log.info("微信加密签名 signature " + signature);

        // 时间戳
        String timestamp = request.getParameter("timestamp");
        log.info("时间戳 timestamp " + timestamp);

        // 随机数
        String nonce = request.getParameter("nonce");
        log.info("随机数 nonce " + nonce);

        // 随机字符串
        String echostr = request.getParameter("echostr");
        log.info("随机字符串 echostr " + echostr);

        PrintWriter out = null;
        try {
            request.setCharacterEncoding("UTF-8");
            log.info("设置 request请求 编码格式为 UTF-8");

            response.setCharacterEncoding("UTF-8");
            log.info("设置 response请求 编码格式为 UTF-8");

            String respMessage = appUserService.push_Message(request, response);
            log.info("controlelr层的 respMessage" + respMessage);

            out = response.getWriter();
            if (SignUtil.checkSignatrue(signature, timestamp, nonce)) {
                log.info("-----------进入了if判断----------");
                out.print(respMessage);
            } else {
                log.info("-----------事件消息推送失败----------");
            }
            log.info("-----------事件消息推送完毕----------");

        } catch (Exception e) {
            log.info("推送消息<------------------->出错", e);
            e.printStackTrace();
        } finally {
            out.close();
            out = null;
        }

    }

    /**
     * 新增APP端用户信息
     *
     * @param userModel 用户模型
     * @return 新增结果
     */
    @ApiOperation(value = "新增APP端用户信息", notes = "新增APP端用户信息")
    @ApiImplicitParam(name = "userModel", value = "用户实体", required = true, dataType = "AppUserModel")
    @RequiresPermissions("admin:appuser:add")
    @PermissionReport(value = "admin:appuser:add", name = "添加帐号", group = "admin_app_user")
    @RequestMapping(value = "/admin/app/user", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public CommonResponse addUser(@RequestBody AppUserModel userModel) {

        CommonResponse commonResponse = CommonResponse.success();

        try {
            appUserService.saveUser(userModel);
        } catch (AppUserException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("add user error, :{}", e);
            commonResponse = CommonResponse.serverError();
        }

        return commonResponse;
    }

    /**
     * 获取用户列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数据量
     * @param keyWord  关键字
     * @return 用户列表
     */
    @ApiOperation(value = "获取APP端用户列表", notes = "获取APP端用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "int"),
            @ApiImplicitParam(name = "pageSize", value = "每页数据量", required = true, dataType = "int"),
            @ApiImplicitParam(name = "keyWord", value = "查询关键字", required = false, dataType = "String")
    })
    @RequestMapping(value = "/admin/app/users", method = RequestMethod.GET)
    public CommonResponse getUsers(int pageNum, int pageSize, String keyWord) {

        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(appUserService.getUsers(pageSize, pageNum, keyWord));
        } catch (Exception e) {
            log.error("get app user list error :{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }

    /**
     * 修改用户信息
     *
     * @param appUserModel 用户信息
     * @return 修改结果
     */
    @ApiOperation(value = "修改APP端用户信息", notes = "修改APP端用户信息")
    @ApiImplicitParam(name = "appUserModel", value = "APP端用户信息", required = true, dataType = "AppUserModel")
    @RequestMapping(value = "/api/app/user", method = RequestMethod.PUT)
    public CommonResponse updateUser(@RequestBody AppUserModel appUserModel) {
        CommonResponse commonResponse = CommonResponse.success();

        try {
            appUserService.updateUser(appUserModel);
        } catch (AppUserException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("update user error, :{}", e);
            commonResponse = CommonResponse.serverError();
        }

        return commonResponse;
    }

    /**
     * 删除用户信息
     *
     * @param id 用户id
     * @return 删除结果
     */
    @ApiOperation(value = "删除APP端用户信息", notes = "删除APP端用户信息")
    @ApiImplicitParam(name = "appUserModel", value = "APP端用户信息", required = true, dataType = "AppUserModel")
    @RequiresPermissions("admin:appuser:delete")
    @PermissionReport(value = "admin:appuser:delete", name = "删除帐号", group = "admin_app_user")
    @RequestMapping(value = "/admin/app/user/{id}", method = RequestMethod.DELETE)
    public CommonResponse deleteUser(@PathVariable(name = "id") long id) {
        CommonResponse commonResponse = CommonResponse.success();

        try {
            appUserService.deleteUser(id);
        } catch (AppUserException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("delete user error, :{}", e);
            commonResponse = CommonResponse.serverError();
        }

        return commonResponse;
    }

    /**
     * APP端用户登录
     *
     * @param appUserModel 登录用户对象
     * @return 登录结果
     */
    @ApiOperation(value = "APP端用户登录", notes = "APP端用户登录")
    @ApiImplicitParam(name = "appUserModel", value = "APP端用户信息", required = true, dataType = "AppUserModel")
    @RequestMapping(value = "/api/app/login", method = RequestMethod.POST)
    public CommonResponse login(@RequestBody AppUserModel appUserModel) {

        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(appUserService.login(appUserModel));
        } catch (AppUserException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("app user login error :{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }


    /**
     * 获取小区列表（app端）
     *
     * @param
     * @return 获取小区列表（app端）
     */
    @ApiOperation(value = "获取小区列表（app端）", notes = "获取小区列表（app端）")
    @ApiImplicitParam(name = "获取小区列表（app端）", value = "获取小区列表（app端）", required = true, dataType = "AppUserModel")
    @RequestMapping(value = "/api/app/getxqlist", method = RequestMethod.GET)
    public CommonResponse getxqlist(int pageSize, int pageNum, String name) {

        CommonResponse commonResponse = CommonResponse.success();

        try {
            commonResponse.setData(appUserService.getxqlist(name, pageSize, pageNum));
        } catch (AppUserException e) {
            commonResponse.setCode(e.getCode());
            commonResponse.setMessage(e.getMessage());
        } catch (Exception e) {
            log.error("app user login error :{}", e);
            commonResponse = CommonResponse.serverError();
        }
        return commonResponse;
    }
}